<template>
  <div>
    <!-- 头部: 搜索栏、面包屑、驱动器设置 -->
    <Header :drive-id="driveId" />

    <!-- 公告区 -->
    <div
      class="zfile-header-announcement"
      v-html="$store.getters.announcement"
      v-if="$store.getters.showAnnouncement"
    ></div>

    <!--
            文件区
            全屏布局：占用满屏
            居中布局: 占用 75% 屏幕, 并垂直居中, 但当屏幕过小时, 还是会恢复全屏.
         -->
    <el-row>
      <el-col
        :offset="isFullScreen ? 0 : 3"
        :xs="24"
        :sm="24"
        :lg="isFullScreen ? 24 : 18"
      >
        <List :drive-id="driveId" ref="List" />
      </el-col>
    </el-row>
    <el-row style="padding-bottom: 70px;padding-left: 30px;">
      <el-button @click="dialogVisible = true">上传</el-button>
      <el-button @click="dialogVisible2 = true">新建文件夹</el-button>
    </el-row>
    <el-dialog title="新建文件夹" :visible.sync="dialogVisible2" width="40%">
      <el-row style="text-align: center">
        <el-input
          type="text"
          v-model="newFolderForm.newFolderName"
          auto-complete="off"
          placeholder="文件夹名"
        ></el-input>
      </el-row>
      <el-row style="text-align: center">
        <el-button @click="createFolder()">确定</el-button>
      </el-row>
      <br />
    </el-dialog>
    <el-dialog title="文件上传" :visible.sync="dialogVisible" width="40%">
      <el-row style="text-align: center">
        <el-upload
          class="upload-demo"
          drag
          :action="uploadUrl"
          ref="upload"
          :multiple="true"
          :show-file-list="true"
          :before-upload="beforeUpload"
        >
          <i class="el-icon-upload"></i>
          <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
        </el-upload>
      </el-row>
      <el-row>
        <el-progress
          :percentage="percent"
          :text-inside="true"
          :stroke-width="15"
          style="width: auto"
        ></el-progress>
      </el-row>
      <br />
    </el-dialog>

    <!-- 文档区 -->
    <el-card
      :class="isFullScreen ? '' : 'zfile-readme-center'"
      v-if="
        $store.getters.showDocument &&
        $store.state.common.config.readme !== null
      "
    >
      <markdown-render :text="$store.state.common.config.readme" />
    </el-card>
  </div>
</template>

<script>
import { log } from 'console';
import Header from './Header.vue';
import List from './List.vue';
import MarkdownRender from './MarkdownRender';

export default {
  name: 'Main',
  props: ['driveId'],
  components: {
    List,
    Header,
    MarkdownRender
  },
  data() {
    return {
      percent: 0,
      dialogVisible: false,
      dialogVisible2: false,
      newFolderForm: {
        newFolderName: "",
        path: ""
      },
      uploadUrl: window.location.hostname + ':8080/app/file/upload'
    };
  },
  methods: {
    beforeUpload(file) {
      var url = 'ws://' + window.location.hostname + ':8080/app/ws';
      var ws = new WebSocket(url);

      ws.onopen = evt => {
        var param = { token: this.$options.methods.getToken() };
        console.log('param:' + JSON.stringify(param));
        ws.send(JSON.stringify(param));
        //连接创建后开始上传文件
        var data = new FormData();
        // 创建一个表单数据
        var pathname = decodeURIComponent(window.location.pathname);
        console.log("path" + pathname)
        var filePath = pathname.substring(pathname.lastIndexOf('main') + 4);
        filePath = decodeURI(filePath);
        if (filePath == null || filePath == '') {
          filePath = '';
        }
        console.log('pathName:' + filePath);
        data.append('file', file);
        data.append('path', filePath);
        data.append('curDeptId', localStorage.getItem("deptId"));
        this.$http.post('/file/upload', data).then(response => {
          this.$message({
            message: '上传中',
            type: 'success',
            duration: 1000
          });
          if (response.data.code === 500) {
            this.$message({
              message: response.data.msg,
              type: 'error',
              duration: 1000
            })
          }
          if (response.data.code === 200) {
            this.$message({
              message: response.data.msg,
              type: 'sucess',
              duration: 1000
            });
            this.dialogVisible = false;
            location.reload()
          }
        });
      };
      ws.onmessage = evt => {
        this.percent = Number.parseInt(evt.data);
      };

      ws.onclose = function (evt) {
        console.log('Connection closed.');
      };
      return false;
    },
    createFolder() {
      //连接创建后开始上传文件
      var data = new FormData();
      // 创建一个表单数据
      var pathname = decodeURIComponent(window.location.pathname);
      var filePath = pathname.substring(pathname.lastIndexOf('main') + 4);
      filePath = decodeURI(filePath);
      if (filePath == null || filePath == '') {
        filePath = '';
      }
      console.log('pathName:' + filePath);
      data.append('newFolderName', this.newFolderForm.newFolderName);
      data.append('path', filePath);
      this.$http.post('/file/newFolder', data).then(response => {
        if (response.data.code === 500) {
          this.$message({
            message: response.data.msg,
            type: 'error',
            duration: 1000
          })
        }
        if (response.data.code === 200) {
          this.$message({
            message: response.data.msg,
            type: 'sucess',
            duration: 1000
          });
          this.dialogVisible2 = false;
          location.reload()
        }
      });
    },
    getToken() {
      var strcookie = document.cookie; //获取cookie字符串
      var arrcookie = strcookie.split('; '); //分割
      //遍历匹配
      for (var i = 0; i < arrcookie.length; i++) {
        var arr = arrcookie[i].split('=');
        if (arr[0] == 'token') {
          // console.log('token:' + arr[1]);
          return arr[1];
        }
      }
      return '';
    }
  },
  watch: {
    // // 如果有自定义 css, js, 则加载到页面上.
    // '$store.state.common.config.customJs': function (newVal) {
    //     let script = document.createElement('script');
    //     script.type = 'text/javascript';
    //     script.text = newVal;
    //     document.getElementsByTagName('head')[0].appendChild(script)
    // },
    // '$store.state.common.config.customCss': function (newVal) {
    //     let style = document.createElement('style');
    //     style.type = 'text/css';
    //     style.innerHTML = newVal;
    //     document.getElementsByTagName('head')[0].appendChild(style)
    // }
  },
  computed: {
    isFullScreen() {
      return this.common.isMobile() || this.$store.getters.layout !== 'center';
    }
  }
};
</script>

<style>
body {
  overflow: hidden;
}

.zfile-readme-center {
  width: 1100px;
  margin: 0 auto;
}

.markdown-body {
  height: 300px;
  overflow-y: auto;
  padding: 0 !important;
  min-width: 100% !important;
}

.zfile-header-announcement {
  background-color: #f4f4f5;
  color: #909399;
  font-size: 12px;
  margin: 0 0 0;
  width: 100%;
  padding: 10px 16px;
  -webkit-box-sizing: border-box;
  box-sizing: border-box;
  border-radius: 4px;
  position: relative;
  overflow: hidden;
  opacity: 1;
  display: -webkit-box;
  display: -ms-flexbox;
  display: flex;
  -webkit-box-align: center;
  -ms-flex-align: center;
  align-items: center;
  -webkit-transition: opacity 0.2s;
  transition: opacity 10s;
}

/* ----- icon 图标样式 ----- */
.icon {
  width: 1em;
  height: 1em;
  vertical-align: -0.15em;
  fill: currentColor;
  overflow: hidden;
}
/* ----- icon 图标样式 ----- */

/* ----- 滚动条样式 ----- */
::-webkit-scrollbar {
  width: 6px;
  height: 8px;
  background: rgba(144, 147, 153, 0.3);
}
::-webkit-scrollbar-button:vertical {
  display: none;
}
::-webkit-scrollbar-track,
::-webkit-scrollbar-corner {
  background-color: #e2e2e2;
}
::-webkit-scrollbar-thumb {
  border-radius: 8px;
  background-color: #a6a6a6;
}
::-webkit-scrollbar-thumb:vertical:hover {
  background-color: #7f7f7f;
}
::-webkit-scrollbar-thumb:vertical:active {
  background-color: rgba(0, 0, 0, 0.38);
}
/* ----- 滚动条样式 ----- */

.el-card__body {
  padding-right: 10px;
}
.el-upload-dragger {
  width: 500px;
  height: 200px;
}
</style>
